/**
 * 
 */
package jvs.peer.xmpp;

import jvs.peer.io.MessageConstant;
import jvs.peer.util.Log;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

/**
 * @author qiangli
 * 
 */
public class XmppPingHandler implements PacketListener, PacketFilter {

	private final static String MSG = "pong";

	private XMPPConnection conn;

	public XmppPingHandler(XMPPConnection conn) {
		this.conn = conn;
		//
	}

	public void processPacket(Packet req) {
		log("@@@ " + this.getClass().getName() + " process packet from: "
				+ req.getFrom() + " id: " + req.getPacketID());
		pong(req.getPacketID(), req.getFrom());
	}

	private void log(String s) {
		
	}

	/**
	 * Only accept ping packet
	 */
	public boolean accept(Packet packet) {
		//allow loopback
		Object obj = packet.getProperty(MessageConstant.PING);
		String from = packet.getFrom();
		String id = packet.getPacketID();
		if (Log.DEBUG) {
			Log.log(this, " accepting id: " + id + " from: " + from
				+ " to: " + packet.getTo());
		}
		return (obj != null && from != null && id != null);
	}

	/**
	 * 
	 * @param id
	 * @param peer
	 */
	private void pong(String id, String peer) {
		Message msg = new Message(peer);
		msg.setThread(id);
		msg.setProperty(MessageConstant.PONG, MSG);
		//
		msg.setSubject(MSG);
		msg.setBody(MSG);
		msg.setType(Message.Type.headline);
		conn.sendPacket(msg);
	}

	public void connect() {
		conn.addPacketListener(this, this);
	}

	public void disconnect() {
		conn.removePacketListener(this);
		conn = null;
	}
}
